<template>
  <div ref="canvasContainer"></div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as THREE from "three";

export default {
  name: "ThreeMap",
  setup() {
    const canvasContainer = ref(null);
    let scene, camera, renderer;

    onMounted(() => {
      // 初始化场景、相机和渲染器
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      canvasContainer.value.appendChild(renderer.domElement);

      // 添加一个立方体
      const geometry = new THREE.BoxGeometry();
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
      const cube = new THREE.Mesh(geometry, material);
      scene.add(cube);

      // 设置相机位置
      camera.position.z = 5;

      // 动画循环
      const animate = () => {
        requestAnimationFrame(animate);

        // 旋转立方体
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;

        renderer.render(scene, camera);
      };

      animate();
    });

    onBeforeUnmount(() => {
      // 清理资源
      renderer.dispose();
    });

    return {
      canvasContainer,
    };
  },
};
</script>

<style scoped></style>
